package m.framework.web;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import m.Config;
import m.framework.beans.MyBeanFactory;
import m.framework.cache.CacheUtil;
import m.framework.cache.MapCache;
import m.framework.utils.StrBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.DispatcherServlet;

/**web全局转发的servlet,启动web的时候加载*/
public class MyDispatcherServlet extends DispatcherServlet {
	private static Logger log = LoggerFactory.getLogger(MyDispatcherServlet.class);
	private static final String utf8="UTF-8";
	
	protected void initFrameworkServlet() throws ServletException {
		super.initFrameworkServlet();
		//初始化cache
		log.info("==============开始初始化初始化系统==============");
		CacheUtil.init(new MapCache());
	}
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		setSystemInfoByReqeust(request);
		
		request.setCharacterEncoding(utf8);
		response.setCharacterEncoding(utf8);
		
		if(request.getRequestURI().endsWith("json")){
			response.setContentType("text/json;charset=UTF-8");
		}else{
			response.setContentType("text/html;charset=UTF-8");
		}
		
		
		Long start = System.currentTimeMillis();
		String req = request.getRequestURI();
		String ip=getIP(request);
		log.info("\n\n\n\n--------------------"+ip+"开始请求" + req + "--------------------");
		if (log.isInfoEnabled()) {
			log.info("参数列表:" + this.getPara(request));
		}
		
		super.service(request, response);
		
		Long consume = System.currentTimeMillis() - start;
		log.info("\n------------------结束请求:" + req + "--" + consume
				+ "ms---------------------");
	}
	
	//通过requet信息设置系统环境
	private void setSystemInfoByReqeust(HttpServletRequest request) {
		if(Config.isInit()){
			return;
		}
		log.info("===========开始初始化境变量=============");
		String webapp=request.getSession().getServletContext().getRealPath("/");
		if(webapp.endsWith("/")||webapp.endsWith("\\")){
			webapp=webapp.substring(0,webapp.length()-1);
		}
		String webRoot=request.getContextPath();
		Config.initByRequest(webRoot,webapp);
		MyBeanFactory.init(this.getWebApplicationContext());
		
		log.info("===========环境变量初始化完毕=============\n"+Config.print());
		
	}

	private String getPara(HttpServletRequest request) {
		Enumeration e = request.getParameterNames();
		StrBuilder sb = new StrBuilder();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			sb.append(name + ":" + request.getParameter(name) + ";");
		}
		return sb.toString();
	}
	
	public static String getIP(HttpServletRequest request) {
		String ip = request.getRemoteAddr();
		// 最后一个为RemoteAddr
		int pos = ip.lastIndexOf(',');
		if (pos >= 0) {
			ip = ip.substring(pos);
		}
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		return ip;
	}
}
